package com.xinnet.mms.customtransfer.service.impl;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xinnet.core.utils.ConfigUtil;
import com.xinnet.core.utils.page.PageView;
import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.customerManage.service.CustomerManageService;
import com.xinnet.mms.customerstate.service.CustomerStateHistService;
import com.xinnet.mms.customtransfer.service.DealWaitChargeCustomerService;
import com.xinnet.mms.empcustomrelation.service.EmpCustomRelationService;
import com.xinnet.mms.entity.CustomStateHist;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.EmpCustomRelation;
import com.xinnet.mms.order.dao.OrderDao;
import com.xinnet.mms.utils.CustomerManage;
import com.xinnet.mms.utils.DateUtil;

@Service("dealWaitChargeCustomerService")
public class DealWaitChargeCustomerServiceImpl implements DealWaitChargeCustomerService{

	@Autowired
	private EmpCustomRelationService empCustomRelationService;
	@Autowired
	private CustomerStateHistService customerStateHistService;
	@Autowired
	private CustomerManageService customerManageService;
	@Autowired
	private CustomAllotService customAllotService;
	
	@Autowired
	private OrderDao orderDao;
	
	private static Logger log=LoggerFactory.getLogger(DealWaitChargeCustomerServiceImpl.class);
	
	@Override
	public void dealWithWaitChargeCustomerService() {
		//
		this.checkNormalorTest();
        log.info("************************************************************************************待续费客户流转开始********************************************"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //分页获取新注册客户信息
        Customer customer = new Customer();
        customer.setCustomType(CustomerManage.DUE_SOON_CUSTOMER);
        int count = empCustomRelationService.getTransferCustomCount(customer);
        
        PageView<Customer> page = new PageView<Customer>();
        page.setPageSize(2000); //每页显示2q条
        page.setRowCount(count);
        long pageCount = page.getPageCount();
        
        for(int i = 1;i<=pageCount;i++){
        	page.setPageNow(i);
        	Integer startPage = page.getFirstResult();
    		customer.setLimitTop(startPage);
    		customer.setLimitDown(page.getPageSize());
        	
        	List<EmpCustomRelation> intentionCustomerList = empCustomRelationService.getTransferCustom(customer);
        	for (Iterator<EmpCustomRelation> iterator = intentionCustomerList.iterator(); iterator.hasNext();) {
    			EmpCustomRelation intentionCustomer = (EmpCustomRelation) iterator.next();
    			this.doSingleCustomer(intentionCustomer);
    		}
        }
		log.info("************************************************************************************待续费客户流转结束********************************************"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
	}
	
	/**
	 * 处理每个客户的流转
	 * @param newRegisterCustom
	 */
	private void doSingleCustomer(EmpCustomRelation intentionCustomer) {
		try {
		//待续费客户流转方向--->>服务期、保护期或是添加新的待续记录
		String customerId = intentionCustomer.getCustomId();
		//要处理的客户
		Customer customer = new Customer();
		//判定截止日期的标志位
		boolean flag = false;
		
		customer = customAllotService.getCustomerById(customerId);
		
		//获取最近一条的待续费期状态记录
		CustomStateHist customStateHistTemp = new CustomStateHist();
		customStateHistTemp.setCustomId(customerId);
		customStateHistTemp.setCustomType(CustomerManage.DUE_SOON_CUSTOMER);
		CustomStateHist customStateHist1 = customerStateHistService.getCustomStateHistByCondition(customStateHistTemp);
		
		//新需求中，待续费客户的停留时间是30天。
		flag = this.checkHoldTime(customStateHist1.getStartTime(),30);
		
		if(flag){
			//获取服务表数据
			List<Customer> customers = this.findAllService(customer);
			
			boolean serviceFlag= false;//产品在服务期则为true
			boolean waitchargeFlag= false;//产品服务期小于截止时间则为true
			//服务期截止时间点  如果小于当前时间，则进入保护期 否则
			if(customers!=null&&customers.size()!=0){
				for(Customer cus : customers){
					if(this.checkHoldTime(cus.getDueTime(), 0)){
						if(this.checkHoldTime(cus.getDueTime(), -30)){
							waitchargeFlag = true;
						}
						serviceFlag = true;
					}
					
				}
			}
			//这里的规则是:
			//1.产品在服务期且到期时间在待续费期范围,则进行添加<待续费期> 记录操作
			//2.产品在服务期且到期时间大于待续费期限范围 ，则进行转入<服务期> 操作
			//3.产品无服务期内产品 ，则进行转入<保护期>操作
			if(serviceFlag&&waitchargeFlag){
				//变更custom表状态
				customer.setCustomerType(CustomerManage.DUE_SOON_CUSTOMER);
				customerManageService.updateCustomer(customer);
				empCustomRelationService.updateEmpCustomRelation(intentionCustomer);
				//添加客户状态变更记录
				CustomStateHist customStateHist=new CustomStateHist();
				customStateHist.setId(UUID.randomUUID().toString());
				customStateHist.setProductId("");
				customStateHist.setCustomId(customer.getCusId());
				customStateHist.setCustomType(CustomerManage.DUE_SOON_CUSTOMER);
				customStateHist.setCustomState(CustomerManage.ACCEPT_YES);
				customStateHist.setEmpId(customer.getEmpId());
				customStateHist.setPusherId("");
				customStateHist.setIsReceive(CustomerManage.ACCEPT_YES);
				customStateHist.setPushHistId("");
				customStateHist.setPushDesc("");
				customStateHist.setProductCode(customer.getProductCode());
				customStateHist.setStartTime(DateUtil.getSysDate().toString());
				customerStateHistService.addCustomerStateHist(customStateHist);
			}
			if(serviceFlag&&!waitchargeFlag){
				//变更custom表状态
				customer.setCustomerType(CustomerManage.SERVICE_CUSTOMER);
				customerManageService.updateCustomer(customer);
				empCustomRelationService.updateEmpCustomRelation(intentionCustomer);
				//添加客户状态变更记录
				CustomStateHist customStateHist=new CustomStateHist();
				customStateHist.setId(UUID.randomUUID().toString());
				customStateHist.setProductId("");
				customStateHist.setCustomId(customer.getCusId());
				customStateHist.setCustomType(CustomerManage.SERVICE_CUSTOMER);
				customStateHist.setCustomState(CustomerManage.ACCEPT_YES);
				customStateHist.setEmpId(customer.getEmpId());
				customStateHist.setPusherId("");
				customStateHist.setIsReceive(CustomerManage.ACCEPT_YES);
				customStateHist.setPushHistId("");
				customStateHist.setPushDesc("");
				customStateHist.setProductCode(customer.getProductCode());
				customStateHist.setStartTime(DateUtil.getSysDate().toString());
				customerStateHistService.addCustomerStateHist(customStateHist);
			}
			if(!serviceFlag&&!waitchargeFlag){
				customer.setCustomerType(CustomerManage.PROTCET_CUSTOMER);
				customerManageService.updateCustomer(customer);
				empCustomRelationService.updateEmpCustomRelation(intentionCustomer);
				//添加客户状态变更记录
				CustomStateHist customStateHist=new CustomStateHist();
				customStateHist.setId(UUID.randomUUID().toString());
				customStateHist.setProductId("");
				customStateHist.setCustomId(customer.getCusId());
				customStateHist.setCustomType(CustomerManage.PROTCET_CUSTOMER);
				customStateHist.setCustomState(CustomerManage.ACCEPT_YES);
				customStateHist.setEmpId(customer.getEmpId());
				customStateHist.setPusherId("");
				customStateHist.setIsReceive(CustomerManage.ACCEPT_YES);
				customStateHist.setPushHistId("");
				customStateHist.setPushDesc("");
				customStateHist.setProductCode(customer.getProductCode());
				customStateHist.setStartTime(DateUtil.getSysDate().toString());
				customerStateHistService.addCustomerStateHist(customStateHist);
			}
		}
		
		} catch (SQLException e) {
			log.info("待续费客户状态流转失败！操作的客户为："+intentionCustomer.getCustomId());
			e.printStackTrace();
		}
	}

	/**
	 * 是否中断流转执行
	 */
	public void checkNormalorTest(){
		//配置文件中默认设置为false，这里没起到控制作用，为了方便测试其他非流程功能，保留以下代码
		String isTest = ConfigUtil.getString("isTest");
        if(isTest==null || "".equals(isTest)){
        	log.error("配置异常：是否是测试环境");
        	return;
        }		
	}
	
	/**
	 * 判断是否超过保留期限  
	 * 
	 * @param customer
	 * @return true 超过  | false 没有超过
	 */
	public boolean checkHoldTime(String createTime,int days){
		boolean result = false;
		//当前时间
		Date now = DateUtil.getSysDate();
		//注册时间
		String addtimeString = createTime;
		Date addtimeDate = DateUtil.parseDateTime(addtimeString);
		//截止时间   ： 注册时间+保留期限
		Date holdDate = DateUtil.addDate(addtimeDate, days);
		
		if(now.after(holdDate)){
			result =  true;
		}else{
			result =  false;
		}
		return result;
	}
	
	/**
	 * 
	 * @param customer
	 */
	public List<Customer> findAllService(Customer customer){
		List<Customer> customers = new ArrayList<Customer>(); 
		List<Customer> customer1 = orderDao.queryIdcService(customer);
		if(customer1!=null&&customer1.size()!=0)
		       customers.addAll(customer1);
		List<Customer> customer2 = orderDao.queryIdcServerService(customer);
		if(customer2!=null&&customer2.size()!=0)
			   customers.addAll(customer2);
		List<Customer> customer3 = orderDao.queryMailboxService(customer);
		if(customer3!=null&&customer3.size()!=0)
		       customers.addAll(customer3);
		List<Customer> customer4 = orderDao.queryOffice365Service(customer);
		if(customer4!=null&&customer4.size()!=0)
			   customers.addAll(customer4);
		List<Customer> customer5 = orderDao.queryNewOfficeService(customer);
		if(customer5!=null&&customer5.size()!=0)
			   customers.addAll(customer5);
		List<Customer> customer6 = orderDao.queryVhostService(customer);
		if(customer6!=null&&customer6.size()!=0)
			   customers.addAll(customer6);
		List<Customer> customer7 = orderDao.queryChiYunService(customer);
		if(customer7!=null&&customer7.size()!=0)
			   customers.addAll(customer7);
		List<Customer> customer8 = orderDao.queryDomainService(customer);
		if(customer8!=null&&customer8.size()!=0)
			   customers.addAll(customer8);
		List<Customer> customer9 = orderDao.queryJianzhanService(customer);
		if(customer9!=null&&customer9.size()!=0)
			   customers.addAll(customer9);
		
		return customers;
		
	}
	
}
